package com.tzy.rpc.register;/**
 * @description:
 * @Author HP
 * @create 2022/3/17 22:04
 */

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.tzy.rpc.enumeration.RpcError;
import com.tzy.rpc.exception.RpcException;
import com.tzy.rpc.loadbalancer.ConsistentHashLoadBalance;
import com.tzy.rpc.loadbalancer.LoadBalancer;
import com.tzy.rpc.loadbalancer.RandomLoadBalancer;
import com.tzy.rpc.util.NacosUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author HP
 * @create 2022-03-17 22:04
 * @desc
 **/
public class NacosServiceDiscovery implements ServiceDiscovery{

    private static final Logger logger= LoggerFactory.getLogger(NacosServiceDiscovery.class);
    private LoadBalancer loadBalancer;
    private static NacosServiceDiscovery nacosServiceDiscovery=new NacosServiceDiscovery(null);

    public NacosServiceDiscovery(LoadBalancer loadBalancer) {
        if (loadBalancer==null){
            this.loadBalancer = new RandomLoadBalancer();
        }else if(loadBalancer instanceof ConsistentHashLoadBalance){
            this.loadBalancer=new ConsistentHashLoadBalance();
        }else {
            setLoadBalancer(loadBalancer);
        }
    }

    public void setLoadBalancer(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
    }

    /**
     * 根据服务名称从注册中心获取到一个服务提供者的地址
     * @param serviceName
     * @return
     */
    @Override
    public InetSocketAddress lookupService(String serviceName) {
        try {
            List<Instance> instances = NacosUtil.getAllInstance(serviceName);
            if(instances.size()==0){
                logger.error("找不到对应服务：" + serviceName);
                throw new RpcException(RpcError.SERVICE_NOT_FOUND);
            }
            Instance instance = loadBalancer.select(instances);
            return new InetSocketAddress(instance.getIp(), instance.getPort());
        } catch (NacosException e) {
            logger.error("获取服务时有错误发生", e);
        }
        return null;
    }
}
